#ifndef __M_FMT_H__
#define __M_FMT_H__

#include "message.hpp"
#include "level.hpp"
#include "util.hpp"
#include <vector>
#include <cassert>
#include <memory>
#include <sstream>

namespace clog
{
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual void format(std::ostream &out, const LogMsg &msg) = 0;
    };
    // 日志消息 时间 等级 线程ID 源文件名称 行号 日志器 换行 制表符 其他
    class MesFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._payload;
        }
    };

    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(const std::string &format = "%H:%M:%S")
            : _format(format)
        {
            if (format.empty())
            {
                _format = "%H:%M:%S";
            }
        }
        void format(std::ostream &out, const LogMsg &msg) override
        {
            struct tm t;
            localtime_r(&msg._ctime, &t);
            char time[128];
            strftime(time, 127, _format.c_str(), &t);
            out << time;
        }

    private:
        std::string _format;
    };
    class LevelFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << LogLevel::toString(msg._level);
        }
    };
    class ThreadFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._tid;
        }
    };
    class FileFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._file;
        }
    };
    class LineFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._line;
        }
    };
    class LoggerFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._logger;
        }
    };
    class NlineFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\n";
        }
    };
    class TabFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\t";
        }
    };
    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(const std::string &str = "")
            : _str(str)
        {
        }
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n")
            : _pattern(pattern)
        {
            assert(parsePattern());
        }
        // 对msg进行格式化
        std::ostream &format(std::ostream &out, const LogMsg &msg)
        {
            for (auto &it : _items)
            {
                it->format(out, msg);
            }

            return out;
        }

        std::string format(const LogMsg &msg)
        {
            std::stringstream ss;
            for (auto &it : _items)
            {
                it->format(ss, msg);
            }

            return ss.str();
        }

        // 根据不同的格式化字符创建不同的格式化子项对象
        /*
            %d ⽇期
            %T 缩进
            %t 线程id
            %p ⽇志级别
            %c ⽇志器名称
            %f ⽂件名
            %l ⾏号
            %m ⽇志消息
            %n 换⾏
        */
    private:
        FormatItem::ptr createItem(const std::string &key, const std::string &val)
        {
            if (key == "d")
                return std::make_shared<TimeFormatItem>(val);
            if (key == "T")
                return std::make_shared<TabFormatItem>();
            if (key == "t")
                return std::make_shared<ThreadFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "c")
                return std::make_shared<LoggerFormatItem>();
            if (key == "f")
                return std::make_shared<FileFormatItem>();
            if (key == "l")
                return std::make_shared<LineFormatItem>();
            if (key == "m")
                return std::make_shared<MesFormatItem>();
            if (key == "n")
                return std::make_shared<NlineFormatItem>();
            if (key == "")
                return std::make_shared<OtherFormatItem>(val);
            std::cout << "不存在该格式化字符：%" << key << std::endl;
            abort();
            return FormatItem::ptr();
        }

        // 对格式化字符串进行解析
        bool parsePattern()
        {
            // 1.提取各个部分的字符串
            std::vector<std::pair<std::string, std::string>> fmt_order;
            size_t pos = 0;
            std::string key, val;
            while (pos < _pattern.size())
            {
                // 判断是否为原始字符
                if (_pattern[pos] != '%')
                {
                    val.push_back(_pattern[pos++]);
                    continue;
                }
                // 此处pos位置为%，判断是否有两个连续的%，两个连续的%充当一个字符%
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    val.push_back('%');
                    pos += 2;
                    continue;
                }

                // 走到这里说明下一个字符为格式化字符，并且原始字符处理完毕
                if (!val.empty())
                {
                    fmt_order.push_back(std::make_pair("", val));
                    val.clear();
                }

                // 处理格式化字符
                pos++;
                if (pos == _pattern.size())
                {
                    std::cout << "%之后没有格式化字符！\n";
                    return false;
                }
                key = _pattern[pos];
                pos++;

                // 格式化字符的下一个位置，判断是否存在子规则
                if (pos < _pattern.size() && _pattern[pos] == '{')
                {
                    pos++; // 指向子规则的起始位置
                    while (pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        val.push_back(_pattern[pos++]);
                    }
                    // 跳出循环 如果走到了格式字符串的末尾 说明不存在}，格式出错
                    if (pos == _pattern.size())
                    {
                        std::cout << "不存在}，格式化字符串格式错误\n";
                        return false;
                    }
                    // 此时pos指向}的位置，向后走一步，走到下一轮新处理的位置
                    pos++;
                }
                fmt_order.push_back(std::make_pair(key, val));
                val.clear();
                key.clear();
            }

            // 创建格式化子项对象，初始化数组_items
            for (auto &it : fmt_order)
            {
                _items.push_back(createItem(it.first, it.second));
            }

            return true;
        }

    private:
        std::string _pattern; // 格式化规则字符串
        std::vector<FormatItem::ptr> _items;
    };

}
#endif